<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter';
import type { VxeGridProps } from '#/adapter';
import { Button, Drawer, Form, Input, Modal, message, Popconfirm, Select } from 'ant-design-vue';
import { deleteLowcodeApi, getLowcodeDetailApi, getLowcodeListApi, saveLowcodeApi } from '#/api/core/lowcode';
import { getOptionsApi, type Option } from '#/api/core/optiontool';
import type { SelectValue } from 'ant-design-vue/es/select';
import { ArrowLeftOutlined } from '@ant-design/icons-vue';

// 修改 props 定义
const props = defineProps<{
  isPreview?: boolean;  // 是否为预览模式
  name?: string;      // 添加 name 属性
}>();

// 添加 emit 定义
const emit = defineEmits<{
  (e: 'back'): void;  // 返回事件
}>();

// 修改 mockConfig 结构，添加 options 定义
const mockConfig = {
  tableName: 'demo',
  columns: [
    { field: 'name', title: '名称', width: 120 },
    { field: 'age', title: '年龄' },
    { field: 'sex', title: '性别' },
    { field: 'level', title: '学历' },
    {
      field: 'status',
      title: '状态',
      formatter: ({ cellValue }: { cellValue: string }) => {
        const optionMap = fieldOptionMaps.value.get('status');
        return optionMap?.get(cellValue)?.label || cellValue;
      }
    },
    {
      field: 'equity',
      title: '权益',
      formatter: ({ cellValue }: { cellValue: string }) => {
        const optionMap = fieldOptionMaps.value.get('equity');
        return optionMap?.get(cellValue)?.label || cellValue;
      }
    },
    {
      field: 'action',
      fixed: 'right' as const,
      title: '操作',
      slots: { default: 'action' },
      width: 160,
    },
  ],
  form: {
    fields: [
      {
        field: 'name',
        label: '名称',
        component: 'Input',
        required: true
      },
      {
        field: 'age',
        label: '年龄',
        component: 'Input',
        required: true
      },
      {
        field: 'sex',
        label: '性别',
        component: 'Input',
        required: false
      },
      {
        field: 'level',
        label: '学历',
        component: 'Input',
        required: true
      },
      {
        field: 'status',
        label: '状态',
        component: 'Select',
        required: true,
        componentProps: {
          optionConfig: {
            type: 'enum',
            source: 'com.matrix.app.common.enums.Equity'
          }
        },
        cascades: ['equity']  // 定义级联关系
      },
      {
        field: 'equity',
        label: '权益',
        component: 'Select',
        required: true,
        componentProps: {
          optionConfig: {
            type: 'service',
            source: 'equityDictService',
            dependOn: 'status'
          }
        }
      },
    ]
  }
};

// 定义表单状态的接口
interface FormState {
  [key: string]: any;
}

const searchText = ref('');
const formState = ref<FormState>({});
const formRef = ref();
const drawerVisible = ref(false);
const drawerTitle = ref('新增');

// 添加选中行数据
const selectedRows = ref<any[]>([]);

// 表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
  },
  columns: [
    { title: '', type: 'checkbox', width: 50 },  // 添加复选框列
    ...mockConfig.columns,
  ],
  toolbarConfig: {
    custom: true,
    buttons: [
      {
        code: 'add',
        name: '新增',
        buttonRender: {
          events: {
            click: handleAdd
          }
        }
      },
    ],
  },
  height: 'auto',
  rowConfig: {
    keyField: 'id',
  },
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getLowcodeListApi(mockConfig.tableName, {
          page: page.currentPage,
          pageSize: page.pageSize,
          search: searchText.value,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

// 添加选项缓存 Map
const optionsCache = ref<Map<string, Option[]>>(new Map());
const fieldOptionMaps = ref<Map<string, Map<string, Option>>>(new Map());

// 修改加载选项的函数为通用函数
async function loadOptions(field: any, filterValue?: string) {
  const { optionConfig } = field.componentProps || {};
  if (!optionConfig) return [];

  const cacheKey = `${optionConfig.type}_${optionConfig.source}_${filterValue || ''}`;
  if (optionsCache.value.has(cacheKey)) {
    return optionsCache.value.get(cacheKey) || [];
  }

  try {
    const data = await getOptionsApi({
      isEnum: optionConfig.type === 'enum',
      pathOrBeanName: optionConfig.source,
      filterConditions: optionConfig.dependOn && filterValue ? {
        [optionConfig.dependOn]: filterValue
      } : undefined
    });
    optionsCache.value.set(cacheKey, data);

    // 更新选项 Map 用于表格显示
    const optionMap = new Map();
    data.forEach(option => {
      optionMap.set(option.value, option);
    });
    if (!fieldOptionMaps.value.has(field.field)) {
      fieldOptionMaps.value.set(field.field, optionMap);
    }

    return data;
  } catch (error) {
    console.error('加载选项失败:', error);
    message.error('加载选项失败');
    return [];
  }
}

// 修改组件挂载逻辑
onMounted(async () => {
  // 加载所有需要选项的字段
  const selectFields = mockConfig.form.fields.filter(
    field => field.component === 'Select' && field.componentProps?.optionConfig
  );

  await Promise.all(selectFields.map(field => loadOptions(field)));
});

// 处理新增按钮点击
function handleAdd() {
  drawerTitle.value = '新增';
  formState.value = {};
  drawerVisible.value = true;
}

// 处理编辑按钮点击
async function handleEdit(row: any) {
  try {
    const data = await getLowcodeDetailApi(mockConfig.tableName, row.id);
    drawerTitle.value = '编辑';
    formState.value = data;

    // 加载所有 Select 字段的选项
    const selectFields = mockConfig.form.fields.filter(
      field => field.component === 'Select'
    );

    // 先加载独立的选项（没有 dependOn 的）
    const independentFields = selectFields.filter(
      field => !field.componentProps?.optionConfig?.dependOn
    );
    await Promise.all(independentFields.map(field => loadOptions(field)));

    // 再加载依赖的选项（有 dependOn 的）
    const dependentFields = selectFields.filter(
      field => field.componentProps?.optionConfig?.dependOn
    );
    for (const field of dependentFields) {
      const dependOnField = field.componentProps?.optionConfig?.dependOn;
      if (dependOnField && formState.value[dependOnField]) {
        await loadOptions(field, String(formState.value[dependOnField]));
      }
    }

    drawerVisible.value = true;
  } catch (error) {
    message.error('获取详情失败');
  }
}

// 处理保存
async function handleSave() {
  try {
    await formRef.value?.validate();
    await saveLowcodeApi(mockConfig.tableName, formState.value);
    message.success('保存成功');
    drawerVisible.value = false;
    gridApi.reload();
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败');
  }
}

// 处理删除
async function handleDelete(row: any) {
  try {
    await deleteLowcodeApi(mockConfig.tableName, row.id);
    message.success('删除成功');
    gridApi.reload();
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  }
}

// 处理取消
function handleCancel() {
  drawerVisible.value = false;
  formRef.value?.resetFields();
}

// 添加批量删除处理函数
function handleDeleteSelected() {
  if (selectedRows.value.length === 0) return;

  const ids = selectedRows.value.map((row) => row.id);

  Modal.confirm({
    title: '批量删除',
    content: `确定要删除选中的 ${ids.length} 条数据吗？`,
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        await Promise.all(ids.map((id) => deleteLowcodeApi(mockConfig.tableName, id)));
        selectedRows.value = [];
        message.success('删除成功');
        gridApi.reload();
      } catch (error) {
        console.error('批量删除失败:', error);
        message.error('删除失败');
      }
    },
  });
}

// 添加表格事件处理
const gridEvents = {
  checkboxChange({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
  checkboxAll({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
};

// 添加状态变更处理函数
async function handleChange(value: SelectValue, field: string[]) {
  if (!value) {
    // 当值为空时,清空级联字段的值
    field.forEach(_field => {
      formState.value[_field].value = undefined;
    });
    return;
  }

  field.forEach(_field => {
    const oneField = mockConfig.form.fields.find(f => f.field === _field);
    if (oneField) {
      formState.value[oneField.field] = undefined;
    }
    if (oneField) {
      loadOptions(oneField, String(value));
    }
  });
}

function getFieldOptions(field: any) {
  const { optionConfig } = field.componentProps || {};
  if (!optionConfig) return [];

  const cacheKey = `${optionConfig.type}_${optionConfig.source}_${optionConfig.dependOn ? formState.value[optionConfig.dependOn] : ''}`;
  return optionsCache.value.get(cacheKey) || [];
}

// 添加返回处理函数
function handleBack() {
  emit('back');
}
</script>

<template>
  <Page auto-content-height>
    <div v-if="props.isPreview" class="preview-container">
      <!-- 预览模式的头部操作区 -->
      <div class="preview-header">
        <div class="header-left">
          <Button @click="handleBack">
            <template #icon><ArrowLeftOutlined /></template>
            返回
          </Button>
          <span class="header-title">
            {{ props.name || '' }}预览
          </span>
        </div>
      </div>

      <!-- 内容区 -->
      <div class="preview-content">
        <Grid class="preview-grid">
          <template #toolbar-actions>
            <Button type="primary" class="mr-2" @click="handleAdd">新增</Button>
            <Button
              v-if="selectedRows.length > 0"
              danger
              type="primary"
              @click="handleDeleteSelected"
            >
              删除
            </Button>
          </template>
          <template #toolbar-tools>
            <Input.Search
              v-model:value="searchText"
              placeholder="请输入搜索内容"
              @search="() => gridApi.reload()"
            />
          </template>
          <template #action="{ row }">
            <Button type="link" @click="() => handleEdit(row)">编辑</Button>
            <Popconfirm
              title="确定要删除吗？"
              @confirm="() => handleDelete(row)"
            >
              <Button type="link" danger>删除</Button>
            </Popconfirm>
          </template>
        </Grid>
      </div>
    </div>

    <template v-else>
      <!-- 非预览模式下的原有内容 -->
      <Grid :grid-events="gridEvents">
        <template #toolbar-actions>
          <Button type="primary" class="mr-2" @click="handleAdd">新增</Button>
          <Button
            v-if="selectedRows.length > 0"
            danger
            type="primary"
            @click="handleDeleteSelected"
          >
            删除
          </Button>
        </template>
        <template #toolbar-tools>
          <Input.Search
            v-model:value="searchText"
            placeholder="请输入搜索内容"
            @search="() => gridApi.reload()"
          />
        </template>
        <template #action="{ row }">
          <Button type="link" @click="() => handleEdit(row)">编辑</Button>
          <Popconfirm
            title="确定要删除吗？"
            @confirm="() => handleDelete(row)"
          >
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </template>
      </Grid>
    </template>

    <Drawer
      :title="drawerTitle"
      :visible="drawerVisible"
      :width="600"
      @close="handleCancel"
    >
      <Form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <template v-for="field in mockConfig.form.fields" :key="field.field">
          <Form.Item
            :label="field.label"
            :name="field.field"
            :rules="[{ required: field.required, message: `请输入${field.label}` }]"
          >
            <template v-if="field.component === 'Input'">
              <Input v-model:value="formState[field.field]" :placeholder="`请输入${field.label}`" />
            </template>
            <template v-else-if="field.component === 'InputNumber'">
              <InputNumber v-model:value="formState[field.field]" :placeholder="`请输入${field.label}`" style="width: 100%" />
            </template>
            <template v-else-if="field.component === 'Select'">
              <Select
                v-model:value="formState[field.field]"
                :options= "getFieldOptions(field)"
                :placeholder="`请选择${field.label}`"
                style="width: 100%"
                @change="(value) => field.cascades? handleChange(value, field.cascades) : undefined"
              />
            </template>
          </Form.Item>
        </template>
      </Form>

      <template #footer>
        <div class="drawer-footer">
          <Button style="margin-right: 8px" @click="handleCancel">取消</Button>
          <Button type="primary" @click="handleSave">确定</Button>
        </div>
      </template>
    </Drawer>
  </Page>
</template>

<style lang="less" scoped>
.preview-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .preview-header {
    flex: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .header-title {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
      }
    }
  }

  .preview-content {
    flex: 1;
    padding: 24px;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .preview-grid {
      width: 100%;
      height: 100%;

      :deep(.vxe-table--main-wrapper) {
        height: 100%;
      }

      :deep(.vxe-table--body-wrapper) {
        min-height: 200px;
      }

      :deep(.vxe-pager) {
        position: relative;
        z-index: 1;
      }
    }
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
  border-top: 1px solid #e9e9e9;
}
</style>
